package com.cxyzy.badgeimageview

import android.annotation.TargetApi
import android.content.Context
import android.graphics.Canvas
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import com.cxyzy.badgeimageview.Badge

class BadgeView : View {
    val badge: Badge
    private var mLayoutWidth = 0
    private var mLayoutHeight = 0
    private var isExactlyDimension = true

    constructor(context: Context?) : super(context) {
        badge = Badge(this, null)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        badge = Badge(this, attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        badge = Badge(this, attrs)
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        badge = Badge(this, attrs)
    }

    public override fun dispatchDraw(canvas: Canvas) {
        super.dispatchDraw(canvas)
        badge.drawBadge(canvas)
    }

    override fun setLayoutParams(params: ViewGroup.LayoutParams) {
        mLayoutWidth = params.width
        mLayoutHeight = params.height
        super.setLayoutParams(params)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        var widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        isExactlyDimension = widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY
        //if (mLayoutWidth == ViewGroup.LayoutParams.WRAP_CONTENT)
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            widthSize = badge.badgeWidth
        } else if (widthMode == MeasureSpec.AT_MOST) {
            widthSize = Math.min(widthSize, badge.badgeWidth)
        }
        //if (mLayoutHeight == ViewGroup.LayoutParams.WRAP_CONTENT)
        if (heightMode == MeasureSpec.UNSPECIFIED) {
            heightSize = badge.badgeHeight
        } else if (heightMode == MeasureSpec.AT_MOST) {
            heightSize = Math.min(heightSize, badge.badgeHeight)
        }
        super.setMeasuredDimension(resolveSize(widthSize, widthMeasureSpec), resolveSize(heightSize, heightMeasureSpec))
    }

    fun refreshBadge() {
        if (mLayoutWidth == ViewGroup.LayoutParams.WRAP_CONTENT || mLayoutHeight == ViewGroup.LayoutParams.WRAP_CONTENT || !isExactlyDimension) {
            super.requestLayout()
        } else {
            super.invalidate()
        }
    }
}